package com.winning.sx.microframework.common.util;

//import com.winning.sx.microframework.common.model.ResultPojo;
import com.winning.sx.microframework.model.ResultPojo;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * Created by xiaoY on 2016/8/23.
 */
public class VisitRest {
    public static ResultPojo postMethod(String url, String method, String param) {
        ResultPojo resultPojo = new ResultPojo();
        try {
            RestTemplate restTemplate = new RestTemplate();
            //方法1
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "text/plain;charset=UTF-8");
            headers.set("Accept", "text/plain;charset=UTF-8");
            //方法2
            //HttpHeaders headers = new HttpHeaders();
            //MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            //headers.setContentType(type);
            //方法3
            //HttpHeaders headers = new HttpHeaders();
            //headers.setContentType(MediaType.APPLICATION_JSON);
            //headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
            ResponseEntity<String> response = restTemplate.postForEntity(url + method, new HttpEntity<String>(param, headers), String.class);
            //无头
            //ResponseEntity<String> response = restTemplate.postForEntity(url + method, param, String.class);
            //？形式
            //ResponseEntity<String> response = restTemplate.postForEntity(url + method + "?param={param}", null, String.class, param);

            int status = Integer.parseInt(String.valueOf(response.getStatusCode()));
            String data = response.getBody();
            resultPojo.setStatus(status);
            resultPojo.setData(data);
        } catch (Exception e) {
            resultPojo.setStatus(500);//服务器异常
            resultPojo.setErrorMsg(e.getMessage());
        }
        return resultPojo;
    }

    public static ResultPojo postMethod(String url) {
        return postMethod(url, "", "");
    }

    public static ResultPojo postMethod(String url, String param) {
        return postMethod(url, "", param);
    }
}
